import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_high_input_page.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_input_page.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_page.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_all_cycle_change_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_all_measures_by_id_and_level_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/danger_investigation_page/hazard_investigation_task_management/on_click_add_page/on_click_add_page_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:jiffy/jiffy.dart';

///隐患排查-》任务信息管理-》点击+新增界面
class OnClickAddPagePage extends StatelessWidget {
  OnClickAddPagePage({super.key});

  final controller = Get.put(OnClickAddPageController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          backgroundColor: AppColors.bg_color_grey,
          appBar: CustomAppBar(
            titleText: controller.addEdit ? '编辑' : '新增',
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.w),
                  padding: EdgeInsets.only(left: 16.w, right: 20.w),
                  color: Colors.white,
                  child: Column(
                    children: [
                      CustomSelectPage(
                          isEnabled: controller.addEdit ? false : true,
                          selectText: '${controller.insertTbBaseMeasuresTaskRequestEntity.riskMeasureIdName}',
                          title: '管控措施描述：',
                          hintText: '请选择',
                          onCallBack: () {
                            Get.toNamed(AppRoutes.doubleGetAllMeasuresSelectionPage, arguments: {
                              'id': controller.levelMeasuresId,
                              'level': controller.level,
                              'isRadio': true,
                            })?.then((value) {
                              final List<GetAllMeasuresByIdAndLevelEntity> selectedList = value as List<GetAllMeasuresByIdAndLevelEntity>;
                              controller.insertTbBaseMeasuresTaskRequestEntity.riskMeasureIdName = selectedList[0].riskMeasureDesc ?? ' ';
                              controller.insertTbBaseMeasuresTaskRequestEntity.riskMeasureId = selectedList[0].id ?? '';
                              controller.isUpdate();
                            });
                          }),
                      CustomHighInputPage(
                        title: '隐患排查内容：',
                        text: controller.insertTbBaseMeasuresTaskRequestEntity.troubleshootContent,
                        onCallBack: (value) {
                          controller.insertTbBaseMeasuresTaskRequestEntity.troubleshootContent = value;
                        },
                        isEnabled: true,
                        isShowDivider: false,
                      ),
                      CustomSelectPage(
                          isEnabled: true,
                          selectText: controller.insertTbBaseMeasuresTaskRequestEntity.controlMeasuresName ?? '',
                          title: '管控手段',
                          hintText: '请选择',
                          onCallBack: () {
                            controller.selectHiddenDangerInvestigationTaskControlMeasuresType();
                          }),
                      CustomSelectPage(
                          isEnabled: true,
                          selectText: controller.insertTbBaseMeasuresTaskRequestEntity.workKindName ?? '',
                          title: '任务类别',
                          hintText: '请选择',
                          onCallBack: () {
                            controller.selectHiddenDangerInvestigationTaskWorkKindType();
                          }),
                      CustomSelectPage(
                          isEnabled: false,
                          isRequired: false,
                          selectText: controller.insertTbBaseMeasuresTaskRequestEntity.instrumentId ?? '',
                          title: '仪表',
                          hintText: '请选择',
                          onCallBack: () {
                            AppToast.showWarning('暂无');
                          }),
                    ],
                  ),
                ),
                Visibility(
                  visible: controller.insertTbBaseMeasuresTaskRequestEntity.isShowSeason,
                  child: Container(
                    margin: EdgeInsets.only(top: 10.w),
                    padding: EdgeInsets.only(left: 10.w, right: 20.w),
                    color: Colors.white,
                    child: Column(
                      children: controller.allCycleChange != null
                          ? controller.allCycleChange!.map((item) {
                              return Column(
                                children: [
                                  AppGaps.vGap16,
                                  _selectItemWidget(item, context),
                                  Container(
                                    color: const Color(0xFFECEEF3),
                                    height: 1.w,
                                  ),
                                  AppGaps.vGap16,
                                ],
                              );
                            }).toList()
                          : [],
                    ),
                  ),
                ),
                Visibility(
                  visible: !controller.insertTbBaseMeasuresTaskRequestEntity.isShowSeason,
                  child: Container(
                    margin: EdgeInsets.only(top: 12.w),
                    padding: EdgeInsets.only(left: 16.w, right: 20.w),
                    color: Colors.white,
                    child: Column(
                      children: [
                        CustomSelectPage(
                            isEnabled: true,
                            selectText: controller.insertTbBaseMeasuresTaskRequestEntity.checkCycleUnitName ?? '',
                            title: '巡检周期单位',
                            hintText: '请选择',
                            onCallBack: () {
                              controller.selectHiddenDangerInvestigationTaskInspectionCycleUnit();
                            }),
                        Visibility(
                          visible: controller.insertTbBaseMeasuresTaskRequestEntity.isShowInputAnd,
                          child: CustomInputPage(
                              textInputType: TextInputType.number,
                              reg: r'^([1-9]|1[0-9]|2[0-3])$',
                              text: '${controller.insertTbBaseMeasuresTaskRequestEntity.checkCycle}',
                              title: '巡检周期',
                              hintText: controller.hintTextContext1,
                              //'请输入整数1~23',
                              onCallBack: (value) {
                                controller.insertTbBaseMeasuresTaskRequestEntity.checkCycle = value;
                              }),
                        ),
                        Visibility(
                          visible: !controller.insertTbBaseMeasuresTaskRequestEntity.isShowInputAnd,
                          child: CustomInputPage(
                            textInputType: TextInputType.number,
                            reg: r'^\d+$',
                            //这个正则表达式的含义是：以1到9中的任意一个数字开头，或者以1后面跟着0到9中的任意一个数字开头，或者以2后面跟着0到3中的任意一个数字开头，然后以这个数字结尾。
                            title: '巡检周期',
                            hintText: controller.hintTextContext2,
                            // '请输入整数',
                            text: '${controller.insertTbBaseMeasuresTaskRequestEntity.checkCycle}',
                            onCallBack: (value) {
                              // AppToast.showError('暂未开发$value');
                              controller.insertTbBaseMeasuresTaskRequestEntity.checkCycle = value;
                            },
                          ),
                        ),
                        Visibility(
                          visible: controller.insertTbBaseMeasuresTaskRequestEntity.isShowTime,
                          child: Column(
                            children: [
                              _selectWidget(
                                  '工作时段',
                                  controller.insertTbBaseMeasuresTaskRequestEntity.workStartTime == ''
                                      ? '请选择'
                                      : '${controller.insertTbBaseMeasuresTaskRequestEntity.workStartTime}至${controller.insertTbBaseMeasuresTaskRequestEntity.workEndTime}',
                                  callback: () {
                                FocusScope.of(context).unfocus();
                                _selectTime();
                              }),
                            ],
                          ),
                        ),
                        Visibility(
                          visible: controller.insertTbBaseMeasuresTaskRequestEntity.isShowInputAnd,
                            child: CustomSelectPage(
                                isRequired: controller.insertTbBaseMeasuresTaskRequestEntity.isShowInputAnd,
                                isEnabled: true,
                                selectText: controller.insertTbBaseMeasuresTaskRequestEntity.workDayTypeName ?? '',
                                title: '工作日类型',
                                hintText: '请选择',
                                onCallBack: () {
                                  controller.selectHiddenDangerInvestigationTaskWorkDayType();
                                })),
                      ],
                    ),
                  ),
                ),
                AppGaps.vGap54,
              ],
            ),
          ),
          bottomSheet: Container(
            width: double.infinity,
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 5.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  width: 108.w,
                  height: 40.w,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xffFFFFFF),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22.r),
                          ),
                          side: BorderSide(
                            color: const Color(0xff5C6DFF),
                            width: 1.w, // 设置边框线的宽度
                          )),
                      onPressed: Get.back,
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xff5C6DFF),
                          fontWeight: FontWeight.w400,
                        ),
                      )),
                ),
                Visibility(
                    visible: controller.addEdit ? false : true,
                    child: SizedBox(
                      width: 125.w,
                      height: 40.w,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xffFFFFFF),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(22.r),
                              ),
                              side: BorderSide(
                                color: const Color(0xff5C6DFF),
                                width: 1.w, // 设置边框线的宽度
                              )),
                          onPressed: () {
                            controller.insertTbBaseMeasuresTask(false);
                          },
                          child: Text(
                            '保存并新增',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: const Color(0xff5C6DFF),
                              fontWeight: FontWeight.w400,
                            ),
                          )),
                    )),
                SizedBox(
                  width: 108.w,
                  height: 40.w,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.blue_button,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(22.r),
                        ),
                      ),
                      onPressed: () {
                        controller.insertTbBaseMeasuresTask(true);
                      },
                      child: Text(
                        '确定',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w400,
                        ),
                      )),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _selectItemWidget(GetAllCycleChangeEntity item, BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _colorfulCheckBox(item),
        Expanded(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            AppGaps.vGap8,
            Text(
              '${item.attribute}',
              style: TextStyle(
                fontWeight: FontWeight.w400,
                fontSize: 14.sp,
                color: const Color(0xFF5C6DFF),
              ),
            ),
            CustomSelectPage(
                isEnabled: true,
                isShowDivider: false,
                selectText: item.checkCycleUnitName!,
                title: '巡检周期单位',
                hintText: '请选择',
                height: 25,
                onCallBack: () {
                  controller.selectInternalHiddenDangerInvestigationTaskInspectionCycleUnit(item);
                }),
            Visibility(
              visible: item.isShowInputAnd,
              child: CustomInputPage(
                  textInputType: TextInputType.number,
                  reg: r'^([1-9]|1[0-9]|2[0-3])$',
                  isShowDivider: false,
                  text: '${item.checkCycle}',
                  title: '巡检周期',
                  hintText: item.hintTextContext1,
                  //'请输入整数1~23'
                  onCallBack: (value) {
                    item.checkCycle = value;
                  }),
            ),
            Visibility(
              visible: !item.isShowInputAnd,
              child: CustomInputPage(
                textInputType: TextInputType.number,
                reg: r'^\d+$',
                isShowDivider: false,
                title: '巡检周期',
                text: '${item.checkCycle}',
                hintText: item.hintTextContext2,
                //'请输入整数'
                onCallBack: (value) {
                  item.checkCycle = value;
                },
              ),
            ),
            Visibility(
              visible: item.isShowTime,
              child: Column(
                children: [
                  _selectWidget(height: 35, vis: false, '工作时段', item.workStartTime == '' ? '请选择' : '${item.workStartTime}至${item.workEndTime}', callback: () {
                    FocusScope.of(context).unfocus();
                    _selectTimeInside(item);
                  }),
                ],
              ),
            ),
            CustomSelectPage(
                isRequired: item.isShowInputAnd,
                height: 35,
                isShowDivider: false,
                isEnabled: true,
                selectText: item.workDayTypeName ?? '',
                title: '工作日类型',
                hintText: '请选择',
                onCallBack: () {
                  controller.selectInternalHiddenDangerInvestigationTaskWorkDayType(item);
                }),
            AppGaps.vGap8,
          ],
        ))
      ],
    );
  }

  Widget _colorfulCheckBox(GetAllCycleChangeEntity item) {
    return Theme(
      data: ThemeData(unselectedWidgetColor: const Color(0xFF3B62FF)),
      child: Checkbox(
          checkColor: const Color(0xFF3B62FF),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          value: item.checkboxSelected,
          onChanged: (value) {
            item.checkboxSelected = !item.checkboxSelected;
            controller.isBool();
          }),
    );
  }

  /// 计划作业开始时间选取
  _selectTime() async {
    final TimeOfDay? selectedTime = await showTimePicker(
      context: Get.context!,
      initialTime: TimeOfDay.now(),
    );
    if (selectedTime != null) {
      controller.insertTbBaseMeasuresTaskRequestEntity.workStartTime =
          Jiffy.parseFromDateTime(DateTime(0000, 00, 00, selectedTime.hour, selectedTime.minute)).format(pattern: 'HH:mm:ss');
      // controller.insertTbBaseMeasuresTaskRequestEntity.workStartTime ='${selectedTime.hour}:${selectedTime.minute}:00';
      controller.update();
      _selectEndTime();
    }
  }

  /// 计划作业开始时间选取
  _selectTimeInside(GetAllCycleChangeEntity item) async {
    final TimeOfDay? selectedTime = await showTimePicker(
      context: Get.context!,
      initialTime: TimeOfDay.now(),
    );
    if (selectedTime != null) {
      item.workStartTime = Jiffy.parseFromDateTime(DateTime(0000, 00, 00, selectedTime.hour, selectedTime.minute)).format(pattern: 'HH:mm:ss');
      controller.update();
      _selectEndTimeInside(item);
    }
  }

  // 计划作业结束时间选取
  _selectEndTime() async {
    final TimeOfDay? selectedTime = await showTimePicker(
      context: Get.context!,
      initialTime: TimeOfDay.now(),
    );
    if (selectedTime != null) {
      controller.insertTbBaseMeasuresTaskRequestEntity.workEndTime =
          Jiffy.parseFromDateTime(DateTime(0000, 00, 00, selectedTime.hour, selectedTime.minute)).format(pattern: 'HH:mm:ss');
      controller.update();
    }
  }

  _selectEndTimeInside(GetAllCycleChangeEntity item) async {
    final TimeOfDay? selectedTime = await showTimePicker(
      context: Get.context!,
      initialTime: TimeOfDay.now(),
    );
    if (selectedTime != null) {
      item.workEndTime = Jiffy.parseFromDateTime(DateTime(0000, 00, 00, selectedTime.hour, selectedTime.minute)).format(pattern: 'HH:mm:ss');
      controller.update();
    }
  }

  /// 选择框 [callback] 选择回调
  Widget _selectWidget(String title, String hintText, {required Function() callback, bool vis = true, int height = 50}) {
    return Column(
      children: [
        Row(
          children: [
            Text(
              '*',
              style: TextStyle(
                fontSize: 16.sp,
                color: AppColors.meaning_color_danger,
              ),
            ),
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                color: AppColors.font_color_black,
              ),
            ),
            Expanded(
              child: SizedBox(
                height: height.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      hintText == '' ? '请选择' : hintText,
                      style: TextStyle(
                        fontSize: 14.sp,
                        height: 1.2,
                        color: AppColors.text_grey,
                      ),
                    ),
                    AppGaps.hGap6,
                    Icon(Icons.arrow_forward_ios, size: 14.sp, color: AppColors.text_grey),
                  ],
                ),
              ),
            ),
          ],
        ),
        Visibility(
          visible: vis,
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Divider(
                height: 1.w,
                color: AppColors.bg_color_grey,
              )),
        ),
      ],
    ).click(callback);
  }
}
